package coreutil

import (
	"fmt"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTrans "github.com/go-playground/validator/v10/translations/zh"

	"strings"
)

var (
	validate = validator.New()
	uniTrans = ut.New(zh.New())
	trans, _ = uniTrans.GetTranslator("zh")
)

func init() {
	err := zhTrans.RegisterDefaultTranslations(validate, trans)
	if err != nil {
		panic(fmt.Sprintf("registerDefaultTranslations fail: %s\n", err.Error()))

	}
}

// 验证struct
func Validate(s interface{}) string {
	err := validate.Struct(s)

	mcls := StructUtil.FindClass(s)
	if err != nil {
		errStrings := []string{}
		for _, err2 := range err.(validator.ValidationErrors) {
			var lineErr = err2.Translate(trans)
			if mcls != nil {
				mf := mcls.FindField(err2.Field())
				if mf != nil {
					lineErr = strings.Replace(lineErr, mf.Ename, mf.Name, -1)
				}
			}
			errStrings = append(errStrings, lineErr)

		}
		return strings.Join(errStrings, ",")
	}
	return ""
}
